package com.yitong.profile.exception;

import javax.validation.ConstraintViolationException;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yitong.base.domain.JsonResponse;

@ControllerAdvice
public class GenericExceptionHandler extends ResponseEntityExceptionHandler {
	/**
	 * 处理RestException.
	 */
	// @ExceptionHandler(value = { RestException.class })
	// public final ResponseEntity<?> handleException(RestException ex,
	// WebRequest request) {
	// HttpHeaders headers = new HttpHeaders();
	// headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8));
	// return handleExceptionInternal(ex, ex.getMessage(), headers, ex.status,
	// request);
	// }

	/**
	 * 处理JSR311 Validation异常.
	 * 
	 * @throws JsonProcessingException
	 */
	@ExceptionHandler(value = { ConstraintViolationException.class, ServiceException.class, RestException.class,
			IllegalArgumentException.class })
	public final ResponseEntity<Object> handleException(ConstraintViolationException ex, WebRequest request)
			throws JsonProcessingException {

		JsonResponse response = new JsonResponse();
		response.setSuccess(false);
		response.setMessage(ex.getMessage());

		ObjectMapper jsonMapper = new ObjectMapper();
		String body = jsonMapper.writeValueAsString(response);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
		return handleExceptionInternal(ex, body, headers, HttpStatus.BAD_REQUEST, request);
	}
}
